package com.ningkang.auth.sms;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 短信工具类
 */
@Component
@Log4j2
public class TelSmsUtils {

    @Autowired
    private Client client;

    /**
     * 短信签名
     */
    @Value("${sms.signName}")
    private String signName;

    /**
     * 模板编号
     */
    @Value("${sms.templateCode}")
    private String templateCode;

    /**
     * 发送单条短信
     *
     * @param tel
     * @param sendDataMap  短信内容
     *
     */
    public SendSmsResponseBody sendSms(String tel, Map<String, String> sendDataMap) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(tel)
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setTemplateParam(JSONObject.toJSONString(sendDataMap));
        SendSmsResponse sendSmsResponse = null;
        try {
            log.info("发送短信验证码：消息内容是：【{}】", JSONObject.toJSONString(sendDataMap));
            sendSmsResponse = client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            log.error("短信发送异常，手机号：【{}】，短信内容：【{}】，异常信息：【{}】", tel, sendDataMap, e);
        }
        return sendSmsResponse.getBody();
    }

}
